package com.jic.market.impl.rest.coupon;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.common.utils.IDUtils;
import com.jic.enums.RedisKey;
import com.jic.market.common.constant.CouponConstant;
import com.jic.market.entity.base.BaseActivity;
import com.jic.market.entity.coupon.CouponConfig;
import com.jic.market.entity.coupon.CouponDetail;
import com.jic.market.enums.CouponIsReceiveEnum;
import com.jic.market.enums.PromotionStatusEnum;
import com.jic.market.mapper.PromotionMemberGradeMapper;
import com.jic.market.mapper.base.BaseActivityMapper;
import com.jic.market.mapper.coupon.CouponConfigMapper;
import com.jic.market.mapper.coupon.CouponDetailMapper;
import com.jic.market.request.rest.coupon.*;
import com.jic.market.request.rest.discount.DiscountQueryRequest;
import com.jic.market.response.rest.coupon.QueryCouponPersonResponse;
import com.jic.market.response.rest.coupon.QueryCouponCenterResponse;
import com.jic.market.service.PromotionMemberGradeService;
import com.jic.market.service.rest.coupon.CouponRestService;
import com.jic.market.service.rest.discount.DiscountService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.GoodsPageQueryRequest;
import com.jic.product.after.response.ProductStoreInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * H5 优惠券
 *
 * @author wwb
 */
@Slf4j
@Service
public class CouponRestServiceImpl implements CouponRestService {

    @Resource
    private BaseActivityMapper baseActivityMapper;
    @Resource
    private CouponConfigMapper couponConfigMapper;
    @Resource
    private CouponDetailMapper couponDetailMapper;
    @Resource
    private ProductListApi productListApi;
    @Resource
    private DiscountService discountService;
    @Autowired
    private PromotionMemberGradeService promotionMemberGradeService;

    @Autowired
    private PromotionMemberGradeMapper promotionMemberGradeMapper;

    @Resource
    private RedisClientTemplate redisClientTemplate;

    private String errorCode = "5000";


    @Override
    public RestResult<PageResult<QueryCouponCenterResponse>> queryCouponCenter(QuyerCouponCenterRequest request) {
        try {
            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_ + request.getToken());
            if (StringUtils.isEmpty(memStr)) {
                return RestResult.error("4000", "登录失效");
            }
            Map<String, Object> memberInfo = JSONArray.parseObject(memStr, HashMap.class);
            request.setStart((request.getStart() - 1) * request.getLimit());
            List<QueryCouponCenterResponse> couponCenterResponseList = baseActivityMapper.queryCouponCenter(CouponConstant.CouponType.COUPON, request.getStart(), request.getLimit(), null, null, null);
            Long total = baseActivityMapper.queryCouponCenterTotal(CouponConstant.CouponType.COUPON, null, null, null);
            if (CollectionUtils.isNotEmpty(couponCenterResponseList)) {
                //查询用户总领取数量
                couponCenterResponseList.forEach(item -> {
                    QueryCouponCenterResponse response = userAvailableNum(item, memberInfo.get("id").toString(),null);
                    item.setUserAvailableNum(response.getUserAvailableNum());
                    item.setIsReceive(response.getIsReceive());
                });
            }
            return RestResult.success(new PageResult<QueryCouponCenterResponse>() {{
                setRows(couponCenterResponseList);
                setTotal(total);
            }});
        } catch (Exception e) {
            log.error("领券中心发生错误====><>>>>>>>>{}", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<Boolean> receiveCoupon(CouponReceiveOfPersonRequest couponReceiveOfPersonRequest) {
        try {
            //根据优惠券编码查询优惠券信息
            BaseActivity baseActivity = baseActivityMapper.queryByPromotionId(couponReceiveOfPersonRequest.getPromotionId());
            CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(couponReceiveOfPersonRequest.getPromotionId());

            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + couponReceiveOfPersonRequest.getToken());

            Map<String, Object> memberInfo = JSONArray.parseObject(memStr, HashMap.class);

            //判断优惠券是否可用
            RestResult restResult = checkCouponAvailable(baseActivity, couponConfig, memberInfo.get("id").toString(), null);
            if (!"0000".equals(restResult.getCode())) {
                //不可用 领取失败
                return restResult;
            } else {
                CouponDetail couponDetail = new CouponDetail();
                //couponDetail.setBusinessId(couponReceiveOfPersonRequest.getAdminOperate().getChildId());
                couponDetail.setPromotionId(baseActivity.getPromotionId());
                couponDetail.setPromName(baseActivity.getPromName());
                couponDetail.setPromType(baseActivity.getPromType());
                couponDetail.setCreateCouponTime(new Date());
                couponDetail.setStartTime(couponConfig.getCouponUseStartTime());
                couponDetail.setEndTime(couponConfig.getCouponUseEndTime());
                couponDetail.setThirdUserId(memberInfo.get("id").toString());
                couponDetail.setStatus(CouponConstant.CouponDetailStatus.REVICE);
                couponDetail.setDeleteFlag(false);
                couponDetail.setCreator(0);
                couponDetail.setDeptId(String.valueOf(baseActivity.getDeptId()));
                couponDetail.setCouponCode(IDUtils.GenerateBillNo());
                long couponFlag = couponDetailMapper.insert(couponDetail);
                return RestResult.success(couponFlag > 0 ? true : false);
            }
        } catch (Exception e) {
            log.error("领券失败===>>>>>>>>>>>>{}", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Override
    public RestResult<PageResult<QueryCouponPersonResponse>> couponListOfPerson(QueryCouponPersonRequest queryCouponPersonRequest) {
        try {
            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_ + queryCouponPersonRequest.getToken());
            if (StringUtils.isEmpty(memStr)) {
                return RestResult.error("4000", "登录失效");
            }
            Map<String, Object> memberInfo = JSONArray.parseObject(memStr, HashMap.class);
            //计算页数
            queryCouponPersonRequest.setStart((queryCouponPersonRequest.getStart() - 1) * queryCouponPersonRequest.getLimit());
            List<QueryCouponPersonResponse> couponPersonResponseList = couponDetailMapper.queryPageDetail(queryCouponPersonRequest.getStart(), queryCouponPersonRequest.getLimit(),
                    queryCouponPersonRequest.getStatus(), memberInfo.get("id").toString(), null);
            Long couponPersonResponseTotal = couponDetailMapper.queryPageDetailTotal(queryCouponPersonRequest.getStatus(), memberInfo.get("id").toString(), null);


//            long removeCount = 0;
//            if(couponPersonResponseList.size() >= 1) {
//                for(int i = couponPersonResponseList.size() - 1; i>=0; i--){
//                    // 过滤等级
//                    Boolean gradeFlag = Boolean.FALSE;
//                    if (StringUtils.isNotBlank(memberInfo.get("id").toString()) && queryCouponPersonRequest.getAdminOperate().getChildId() != null) {
//                        BaseActivity baseActivity = baseActivityMapper.queryByPromotionId(couponPersonResponseList.get(i).getPromotionId());
//                        if (null != baseActivity) {
//                            PromotionMemberGrade promotionMemberGradeQ = new PromotionMemberGrade();
//                            promotionMemberGradeQ.setPromotionCode(couponPersonResponseList.get(i).getPromotionId());
//                            promotionMemberGradeQ.setDeleteFlag(false);
//                            List<PromotionMemberGrade> promotionMemberGradeList = promotionMemberGradeMapper.query(promotionMemberGradeQ);
//                            gradeFlag = promotionMemberGradeService.checkPromotion(memberInfo.get("id").toString(), queryCouponPersonRequest.getAdminOperate().getChildId().toString(), baseActivity.getChannelCodes(), promotionMemberGradeList);
//                        }
//                    }
//                    if (!gradeFlag) {
//                        couponPersonResponseList.remove(i);
//                        removeCount++;
//                    }
//                }
//            }
//            couponPersonResponseTotal = couponPersonResponseTotal - removeCount;
//            Long finalCouponPersonResponseTotal = couponPersonResponseTotal;

            return RestResult.success(new PageResult<QueryCouponPersonResponse>() {{
                setRows(couponPersonResponseList);
                setTotal(couponPersonResponseTotal);
            }});
        } catch (Exception e) {
            log.error("查询个人中心优惠券失败===>>>>>>>>>>{}", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Override
    public RestResult<PageResult<QueryCouponCenterResponse>> queryCouponByThirdProductCode(CouponListOfGoodsRequest couponListOfGoodsRequest) {
        try {
            Map<String, Object> memberInfo = null;
            if (StringUtils.isNotEmpty(couponListOfGoodsRequest.getToken())) {
                String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_ + couponListOfGoodsRequest.getToken());
                if (org.apache.commons.lang3.StringUtils.isEmpty(memStr)) {
                    return RestResult.error("4000", "登录失效");
                }
                memberInfo = JSONArray.parseObject(memStr, HashMap.class);
            }

            couponListOfGoodsRequest.setStart((couponListOfGoodsRequest.getStart() - 1) * couponListOfGoodsRequest.getLimit());

            List<ProductStoreInfo> productStoreInfos = productListApi.queryProductBySpuList(new GoodsPageQueryRequest() {{
                setId(couponListOfGoodsRequest.getMpId());
            }});

            if (CollectionUtils.isEmpty(productStoreInfos)) {
                return RestResult.error("9999", "商品不存在");
            }
            ProductStoreInfo goods = productStoreInfos.get(0);

            List<QueryCouponCenterResponse> couponCenterResponseList = baseActivityMapper.queryCouponCenter(CouponConstant.CouponType.COUPON, couponListOfGoodsRequest.getStart(),
                    couponListOfGoodsRequest.getLimit(), couponListOfGoodsRequest.getMpId().toString(), null, null);
            Long total = baseActivityMapper.queryCouponCenterTotal(CouponConstant.CouponType.COUPON, couponListOfGoodsRequest.getMpId().toString(), null, null);
            if (memberInfo != null) {
                //查询用户总领取数量
                Map<String, Object> finalMemberInfo = memberInfo;
                couponCenterResponseList.forEach(item -> {
                    QueryCouponCenterResponse response = userAvailableNum(item,finalMemberInfo.get("id").toString(),null);
                    item.setUserAvailableNum(response.getUserAvailableNum());
                    item.setIsReceive(response.getIsReceive());
                });
            }
            return RestResult.success(new PageResult<QueryCouponCenterResponse>() {{
                setRows(couponCenterResponseList);
                setTotal(total);
            }});
        } catch (Exception e) {
            log.error("根据商品编码查询优惠券列表失败==>>>{}", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Override
    public RestResult<List<QueryCouponPersonResponse>> settlementMyCouponList(SettlementMyCouponRequest settlementMyCouponRequest) {
        try {

            String userStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_ + settlementMyCouponRequest.getToken());
            if (StringUtils.isEmpty(userStr)) {
                return RestResult.error("4000", "登录失效");
            }

            Map<String, Object> userInfo = JSONObject.parseObject(userStr, HashMap.class);

            //查询用户所有优惠券
            List<QueryCouponPersonResponse> restList = couponDetailMapper.queryMyCouponList(userInfo.get("id").toString());
            if (CollectionUtils.isNotEmpty(settlementMyCouponRequest.getSettlementCouponRequestList())) {
                settlementMyCouponRequest.getSettlementCouponRequestList().forEach(settlementCouponRequest -> {
                    restList.forEach(queryCouponPersonResponse -> {
                        if (queryCouponPersonResponse.getCouponCode().equals(settlementCouponRequest.getCouponCode())) {
                            queryCouponPersonResponse.setSelected(true);
                        } else {
                            queryCouponPersonResponse.setSelected(false);
                        }
                    });
                });
                log.info("查询用户是否选中=============>>>>>>>>>>>>>>>>数据格式化===========>>>>结果:{}", JSONArray.toJSONString(restList));
            }

            DiscountQueryRequest discountQueryRequest = new DiscountQueryRequest();
            discountQueryRequest.setPromotionGoodsList(settlementMyCouponRequest.getSettlementProductList());
            discountQueryRequest.setCouponCodeInfoList(restList);
            discountQueryRequest.setThirdUserId(userInfo.get("id").toString());
//            discountQueryRequest.setChannelCode(settlementMyCouponRequest.getAdminOperate().getChildId().toString());
//            discountQueryRequest.setAdminOperate(settlementMyCouponRequest.getAdminOperate());
            List<QueryCouponPersonResponse> responses = discountService.queryCoupon(discountQueryRequest);
            return RestResult.success(responses);
        } catch (Exception e) {
            log.error("结算页查询优惠券列表失败==================={}", e);
            return RestResult.error(errorCode, e.getMessage());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResult<Boolean> useCoupons(UseCouponRequest useCouponRequest) {
        try {
            List<CouponDetail> couponDetailList = couponDetailMapper.query(new CouponDetail() {{
                setThirdUserId(useCouponRequest.getUserId());
                setCouponCode(useCouponRequest.getCouponCode());
            }});
            if (CollectionUtils.isEmpty(couponDetailList)) {
                return RestResult.error("9999", "优惠券不存在");
            }
            CouponDetail couponDetail = couponDetailList.get(0);
            if (!couponDetail.getStatus().equals(CouponConstant.CouponDetailStatus.REVICE)) {
                return RestResult.error("9999", "优惠券已过期或已使用");
            }

            couponDetailMapper.update(new CouponDetail() {{
                setId(couponDetail.getId());
                setThirdUserId(useCouponRequest.getUserId());
                setStatus(CouponConstant.CouponDetailStatus.USE);
                setUseMobile(useCouponRequest.getUsePhone());
                setOrderNo(useCouponRequest.getOrderCode());
                setUpdateTime(new Date());
            }});
            log.info("优惠券使用===》》》{}", useCouponRequest.getCouponCode());
            return RestResult.success(true);
        } catch (Exception e) {
            log.info("使用优惠券错误===>>>{}", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Override
    public RestResult<Boolean> returnCoupon(ReturnCouponRequest returnCouponRequest) {
        try {
            List<CouponDetail> useCouponList = couponDetailMapper.query(new CouponDetail() {{
                setCouponCode(returnCouponRequest.getCouponCode());
                setThirdUserId(returnCouponRequest.getUserId());
                setStatus(CouponConstant.CouponDetailStatus.USE);
            }});
            if (CollectionUtils.isEmpty(useCouponList)) {
                return RestResult.error("9999", "优惠券不存在");
            }

            CouponDetail couponDetail = useCouponList.get(0);

            couponDetailMapper.update(new CouponDetail() {{
                setOrderNo("");
                setStatus(CouponConstant.CouponDetailStatus.REVICE);
                setUpdateTime(new Date());
            }});
            log.info("优惠券退回===>>>>{}", returnCouponRequest.getCouponCode());
            return RestResult.success(true);
        } catch (Exception e) {
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    /**
     * 查询优惠券信息
     * @param quyerCouponCenterRequest
     * @return
     */
    @Override
    public RestResult<QueryCouponCenterResponse> queryCouponInfo(QuyerCouponCenterRequest quyerCouponCenterRequest) {
        try {
            List<CouponDetail> couponDetailList = couponDetailMapper.query(new CouponDetail() {{
                setCouponCode(quyerCouponCenterRequest.getCouponCode());
            }});
            if (CollectionUtils.isEmpty(couponDetailList)) {
                return RestResult.error("9999", "优惠券不存在");
            }
            CouponDetail couponDetail = couponDetailList.get(0);
            if (!couponDetail.getStatus().equals(CouponConstant.CouponDetailStatus.REVICE)) {
                return RestResult.error("9999", "优惠券已过期或已使用");
            }
            QueryCouponCenterResponse response = new QueryCouponCenterResponse();
            BeanUtils.copyProperties(couponDetail,response);
            return RestResult.success(response);
        } catch (Exception e) {
            log.info("查询优惠券错误===>>>{}", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }

    @Override
    public RestResult<PageResult<QueryCouponCenterResponse>> getPhoneCouponCenter(QuyerCouponCenterRequest request) {
        try {
            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_ + request.getToken());
            if (StringUtils.isEmpty(memStr)) {
                return RestResult.error("4000", "登录失效");
            }
            Map<String, Object> memberInfo = JSONArray.parseObject(memStr, HashMap.class);
            request.setStart((request.getStart() - 1) * request.getLimit());
            List<QueryCouponCenterResponse> couponCenterResponseList = baseActivityMapper.queryCouponCenter(CouponConstant.CouponType.COUPON, request.getStart(), request.getLimit(), null, null,request.getAmountDeductType());
            Long total = baseActivityMapper.queryCouponCenterTotal(CouponConstant.CouponType.COUPON, null, null,request.getAmountDeductType());
            if (CollectionUtils.isNotEmpty(couponCenterResponseList)) {
                //查询用户总领取数量
                couponCenterResponseList.forEach(item -> {
                    QueryCouponCenterResponse response = userAvailableNum(item, memberInfo.get("id").toString(),null);
                    item.setUserAvailableNum(response.getUserAvailableNum());
                    item.setIsReceive(response.getIsReceive());
                    //TODO 获取积分通兑规则 计算兑换所需积分
                    item.setAmountDeductTypeDesc("话费抵用券");
                    item.setCouponAmount(item.getCouponAmount().setScale(1,BigDecimal.ROUND_DOWN));
                    item.setPointsCouponNum(item.getCouponAmount().multiply(new BigDecimal(100)));
                });
            }
            return RestResult.success(new PageResult<QueryCouponCenterResponse>() {{
                setRows(couponCenterResponseList);
                setTotal(total);
            }});
        } catch (Exception e) {
            log.error("领券中心发生错误====><>>>>>>>>{}", e);
            return RestResult.error("9999", "服务器错误, 请稍后...");
        }
    }


    /**
     * 判断优惠券是否可用
     *
     * @param baseActivity
     * @param couponConfig
     * @param thirdUserId  第三方用户id
     * @return
     */
    private RestResult checkCouponAvailable(BaseActivity baseActivity, CouponConfig couponConfig, String thirdUserId, Long businessId) {
        if (null == baseActivity) {
            return RestResult.error(errorCode, "优惠券不存在");
        }
        //是否是审核通过
        log.info(baseActivity.getStatus());
        log.info(PromotionStatusEnum.AUDIT_PASS.getCode().toString());
        if (!baseActivity.getStatus().equals(PromotionStatusEnum.AUDIT_PASS.getCode().toString())) {
            log.info("校验是否审核通过===========>>>>{}", baseActivity.getStatus());
            return RestResult.error("5001", "优惠券未通过审核");
        }
        //是否可用
        if (baseActivity.getStartTime().getTime() > System.currentTimeMillis() && couponConfig.getCouponUseStartTime().getTime() > System.currentTimeMillis()) {
            log.info("校验开始时间是否大于当前时间===========>>>>{}===>>>>>>{}", baseActivity.getStartTime().getTime(), couponConfig.getCouponUseStartTime().getTime());
            return RestResult.error("5002", "优惠券活动未开始");
        }
        if (baseActivity.getEndTime().getTime() < System.currentTimeMillis() && couponConfig.getCouponUseEndTime().getTime() < System.currentTimeMillis()) {
            log.info("校验结束时间是否小于当前时间===========>>>>{}===>>>>>>{}", baseActivity.getEndTime().getTime(), couponConfig.getCouponUseEndTime().getTime());
            return RestResult.error("5003", "优惠券活动已过期");
        }
        //发放总数
        if (null != couponConfig.getGrantTotalNum()) {
            Long total = couponDetailMapper.queryTotalByPromotionId(baseActivity.getPromotionId(), businessId);
            log.info("校验发放总数===========>>>>{}===>>>>>>{}", couponConfig.getGrantTotalNum(), total);
            if (Long.valueOf(couponConfig.getGrantTotalNum()) <= total) {
                return RestResult.error("5004", "优惠券数量不足");
            }
        }
        if (null != couponConfig.getIdLimitDayNum()) {
            //查询用户当天领取数量
            Long limitDayNum = couponDetailMapper.queryLimitDayNumByThirdUserId(thirdUserId, baseActivity.getPromotionId(), businessId);
            log.info("校验用户当天领取数量===========>>>>{}===>>>>>>{}", couponConfig.getIdLimitDayNum(), limitDayNum);
            if (limitDayNum != null && limitDayNum >= Long.valueOf(couponConfig.getIdLimitDayNum())) {
                return RestResult.error("5005", "当前账号每日领取数量超过限制");
            }
        }
        if (null != couponConfig.getIdLimitNum()) {
            //查询用户当前总领取数量
            Long limitNum = couponDetailMapper.queryLimitNumByThirdUserId(thirdUserId, baseActivity.getPromotionId(), businessId);
            log.info("校验用户当前总领取数量===========>>>>{}===>>>>>>{}", couponConfig.getIdLimitNum(), limitNum);
            if (limitNum != null && limitNum >= Long.valueOf(couponConfig.getIdLimitNum())) {
                return RestResult.error("5006", "当前账号总领取数量超过限制");
            }
        }
        return RestResult.success("可用");
    }

    /**
     * 计算用户可领取数量
     *
     * @param queryCouponCenterResponse
     * @param thirdUserId
     * @return
     */
    private QueryCouponCenterResponse userAvailableNum(QueryCouponCenterResponse queryCouponCenterResponse, String thirdUserId, Long businessId) {
        QueryCouponCenterResponse response = new QueryCouponCenterResponse();
        //查询当前用户是否领取该优惠券
        Long limitNum = couponDetailMapper.queryLimitNumByThirdUserId(thirdUserId , queryCouponCenterResponse.getPromotionId(),businessId);
        if (limitNum != null && limitNum > 0){
            response.setIsReceive(CouponIsReceiveEnum.RECEIVE_ENUM_TRUE.getCode());
        }else {
            response.setIsReceive(CouponIsReceiveEnum.RECEIVE_ENUM_FALSE.getCode());
        }
        if (null != queryCouponCenterResponse.getGrantTotalNum()){
            Long total = couponDetailMapper.queryTotalByPromotionId(queryCouponCenterResponse.getPromotionId(),businessId);
            log.info("校验发放总数===========>>>>{}===>>>>>>{}", queryCouponCenterResponse.getGrantTotalNum(),total);
            if(Long.valueOf(queryCouponCenterResponse.getGrantTotalNum()) <= total){
                response.setUserAvailableNum(0L);
                return response;
            }
        }
        if (null != queryCouponCenterResponse.getIdLimitDayNum()){
            //查询用户当天领取数量
            Long limitDayNum = couponDetailMapper.queryLimitDayNumByThirdUserId(thirdUserId , queryCouponCenterResponse.getPromotionId(),businessId);
            log.info("校验用户当天领取数量===========>>>>{}===>>>>>>{}", queryCouponCenterResponse.getIdLimitDayNum(),limitDayNum);
            if (limitDayNum != null && limitDayNum >= Long.valueOf(queryCouponCenterResponse.getIdLimitDayNum())){
                response.setUserAvailableNum(0L);
                return response;
            }else{
                if(null != queryCouponCenterResponse.getIdLimitNum()){
                    //查询用户当前总领取数量
                    log.info("校验用户当前总领取数量===========>>>>{}===>>>>>>{}", queryCouponCenterResponse.getIdLimitNum(),limitNum);
                    if (limitNum != null && limitNum >= Long.valueOf(queryCouponCenterResponse.getIdLimitNum())){
                        response.setUserAvailableNum(0L);
                        return response;
                    }
                }
                Long restInte = queryCouponCenterResponse.getIdLimitDayNum() - limitDayNum;
                response.setUserAvailableNum(restInte);
                return response;
            }
        }
        if(null != queryCouponCenterResponse.getIdLimitNum()){
            //查询用户当前总领取数量
            log.info("校验用户当前总领取数量===========>>>>{}===>>>>>>{}", queryCouponCenterResponse.getIdLimitNum(),limitNum);
            if (limitNum != null && limitNum >= Long.valueOf(queryCouponCenterResponse.getIdLimitNum())){
                response.setUserAvailableNum(0L);
                return response;
            }else{
                Long restInte = queryCouponCenterResponse.getIdLimitNum() - limitNum;
                response.setUserAvailableNum(restInte);
                return response;
            }
        }
        return response;
    }

}
